package com.iakuil.app.common.ws.listener;

import com.iakuil.app.common.core.constant.RedisConstant;
import com.iakuil.app.common.redis.base.RedisTopicListener;
import com.iakuil.app.common.ws.utils.WsSessionUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

/**
 * 广播消息监听器
 *
 * <p>基于Redis Pub/Sub，订阅广播Channel，发送消息给所有本地会话。
 * <p>广播示例：redisTemplate.convertAndSend(RedisConstant.WS_BROADCAST_CHANNEL, msg)
 *
 * @author Kai
 */
@Component
public class BroadcastRedisMessageListener implements RedisTopicListener {

    private final RedisTemplate<String, Object> redisTemplate;

    public BroadcastRedisMessageListener(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] messageBody = message.getBody();
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        if (msg != null) {
            WsSessionUtils.sendToAll(String.valueOf(msg));
        }
    }

    @Override
    public Topic getTopic() {
        return new ChannelTopic(RedisConstant.WS_BROADCAST_CHANNEL);
    }
}
